package com.example.myproject.server;

import com.example.myproject.client.GreetingService;
import com.example.myproject.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 10 characters long");
		}
		
		String strLine,Response="",LastwordinLine=null;
		int numline=0; //line number counter
		// split the input contents with new line delimeter
		  String[] numberofLines=input.split("\n");
		  for(int i=0;i<numberofLines.length;i++){
			  numline++;
			  strLine=numberofLines[i]; // parsing each line
			  //System.out.println(strLine);
				// split the contents of line with space
				  String[] WordsinLine=strLine.split(" ");
				
				// check for the first word with prior line last word. this needs to be done from second line
				  if(numline > 1)
				  {
				  if(WordsinLine[0].equals(LastwordinLine))
					  Response=Response+"Repeated word on line " + numline + ": " +WordsinLine[0]+" " +LastwordinLine+"<br>"; //added <br> tag at end
				  }
				   
				  //check for consecutive repeated words within word array after split
				  for(int j=0;j< WordsinLine.length-1;j++)
				  {
					  if (WordsinLine [j].equals (WordsinLine [j+1]))
						  Response=Response+"Repeated word on line " + numline + ": " + WordsinLine [j]+" "+WordsinLine[j+1]+"<br>";
				  }
				  //update last work to check with next line first word
				  if (numline>1)
					 LastwordinLine=WordsinLine [WordsinLine.length-1];
				  //System.out.println(LastwordinLine);
				  
			  
		  }
		  if(Response=="")
			  Response="No repeated words found";
		//String serverInfo = getServletContext().getServerInfo();
		//String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		//userAgent = escapeHtml(userAgent);

		return Response;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
